//
//  WKWebViewController.m
//  UIKitLearn
//
//  Created by 李旭阳[产品技术中心] on 2020/5/27.
//  Copyright © 2020 李旭阳[产品技术中心]. All rights reserved.
//

#import "WKWebViewController.h"
#import <WebKit/WebKit.h>
#import "UIView+Toast.h"


@interface WKWebViewController ()
@property (nonatomic, strong) WKWebView *webView;
@end

@implementation WKWebViewController

- (void)loadView {

    WKWebViewConfiguration *webConfiguration = [WKWebViewConfiguration new];
    webConfiguration.dataDetectorTypes = WKDataDetectorTypePhoneNumber;
    _webView = [[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds configuration:webConfiguration];
    _webView.backgroundColor = [UIColor whiteColor];
    // 允许左滑右滑手势
    _webView.allowsBackForwardNavigationGestures = YES;
    self.view = _webView;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupUI];

}

- (void)setupUI{
    

    //YES航栏的属性默认 YES是透明效果并且主view不会偏移
    self.navigationController.navigationBar.translucent = YES;

    self.title = @"WKWebView基本使用";
//    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"WKBack" style:UIBarButtonItemStylePlain target:self action:@selector(leftItemClicked:)];
//    self.navigationItem.leftBarButtonItem = backItem;




    CGFloat toolBarH = 44.0;
    UIToolbar *toolBar = [[UIToolbar alloc] init];
    toolBar.barTintColor = [UIColor lightGrayColor];
    toolBar.frame = (CGRect){.0, CGRectGetHeight(self.view.frame) - toolBarH - [[UIApplication sharedApplication].windows firstObject].safeAreaInsets.bottom, CGRectGetWidth(self.view.frame), toolBarH};
    [self.view addSubview:toolBar];
    
    UIBarButtonItem *forwardItem = [[UIBarButtonItem alloc] initWithTitle:@"➡️" style:UIBarButtonItemStyleDone  target:self action:@selector(forwardButtonClicked:)];
    UIBarButtonItem *backwardItem = [[UIBarButtonItem alloc] initWithTitle:@"🔙" style:UIBarButtonItemStyleDone target:self action:@selector(backwardButtonClicked:)];
    UIBarButtonItem *refreshItem = [[UIBarButtonItem alloc] initWithTitle:@"refresh" style:UIBarButtonItemStyleDone target:self action:@selector(backwardButtonClicked:)];
    UIBarButtonItem *backforwardListItem = [[UIBarButtonItem alloc] initWithTitle:@"List" style:UIBarButtonItemStyleDone target:self action:@selector(backforwardListItemClicked:)];
    UIBarButtonItem *inputWebsite = [[UIBarButtonItem alloc] initWithTitle:@"input" style:UIBarButtonItemStyleDone target:self action:@selector(inputItemClicked:)];
    UIBarButtonItem *snapItem = [[UIBarButtonItem alloc] initWithTitle:@"snap" style:UIBarButtonItemStyleDone target:self action:@selector(snapItemClicked:)];
    
    toolBar.items = @[backwardItem,forwardItem,refreshItem, backforwardListItem, inputWebsite,snapItem];
    
   // NSString *urlStr = @"https://www.baidu.com";
   //  NSString *urlStr = @"https://www.apple.com";
    NSString *vipshopUrlStr = @"https://www.vip.com";
    
    NSURL *url = [NSURL URLWithString:vipshopUrlStr];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    [_webView loadRequest:request];
    

}
#pragma mark - Actions

- (void)leftItemClicked:(UIButton *)sender {
    
    if ([_webView canGoBack]) {
        [_webView goBack];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}


- (void)forwardButtonClicked:(UIButton *)sender {
    
    if ([_webView canGoForward]) {
        [_webView goForward];
    }
}


- (void)backwardButtonClicked:(UIButton *)sender {
    
    if ([_webView canGoBack]) {
        [_webView goBack];
    }
}


- (void)refreshButtonClicked:(UIButton *)sender {
    
    [_webView reload];
}


- (void)backforwardListItemClicked:(UIBarButtonItem *) sender {
    
    NSLog(@"%s", __FUNCTION__);
    if (_webView.backForwardList.forwardList.count > 0) {
        NSLog(@"forwardItem");
        NSLog(@"title：%@", _webView.backForwardList.forwardItem.title);
        NSLog(@"URL：%@", _webView.backForwardList.forwardItem.URL);
    }
    if (_webView.backForwardList.backList.count > 0) {
        NSLog(@"backwardItem");
        NSLog(@"title：%@", _webView.backForwardList.backItem.title);
        NSLog(@"URL：%@", _webView.backForwardList.backItem.URL);
    }
}


- (void)inputItemClicked:(UIBarButtonItem *)sender {
    
       NSString *title = NSLocalizedString(@"website", nil);
       NSString *message = NSLocalizedString(@"input", nil);
       NSString *cancelButtonTitle = NSLocalizedString(@"Cancel", nil);
       NSString *otherButtonTitle = NSLocalizedString(@"OK", nil);
       
    
       UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
           //增加取消按钮；
       [alertController addAction:[UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {}]];
        //增加确定按钮；
       [alertController addAction:[UIAlertAction actionWithTitle:otherButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
           
           UITextField * wordNameTextField = alertController.textFields.firstObject;//获取到textField
           
           if ( wordNameTextField.text.length != 0) {
                 
               
                NSString *urlStr = wordNameTextField.text;
               NSLog(@"",urlStr);
               [self.view makeToast:urlStr];
                NSURL *url = [NSURL URLWithString:urlStr];
                NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
               [self.webView loadRequest: request];
           }
        

        
       }]];
       
        [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.placeholder = nil;
        }];

       [self presentViewController:alertController animated:true completion:nil];
    
}

- (void)snapItemClicked:(UIBarButtonItem *)sender {
    
    WKSnapshotConfiguration *snapConfig = [[WKSnapshotConfiguration alloc] init];
    [_webView takeSnapshotWithConfiguration:snapConfig completionHandler:^(UIImage * _Nullable snapshotImage, NSError * _Nullable error) {
        if (!error) {
            NSLog(@"%@", snapshotImage);
             UIImageWriteToSavedPhotosAlbum(snapshotImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        } else {
            NSLog(@"error：%@", error);
        }
    }];
}


-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    NSString *msg = nil;
    if(error){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
    }
    NSLog(@"%@", msg);
}


@end
